<template>
	<!-- 上传视频或者图片 -->
	<view class="up-page">
		<!--图片-->
		<view class="show-box" v-for="(item,index) in imageList" :key="index">
			<image class="full" :src="item" :data-src="image" @tap="previewImage(item)">
			</image>
			<view class="delect-icon" @tap="delect(index)">
				<image class="full clear" :src="clearIcon"  mode=""></image>
				<!--图片或者视频上传成功了，点击右上角叉号-->
			</view>
		</view>
		<!--视频-->
		<view class="show-box" v-for="(item1, index1) in videoList" :key="index1">
			<video :enableNative="true" class="full" :src="item1"></video>
			<view class="delect-icon" @tap="delectVideo(index1)">
				<image class="full" :src="clearIcon" mode=""></image>
			</view>
		</view>
		<view v-if="VideoOfImagesShow" @tap="chooseVideoImage" class="box-mode">
			<image v-if="loading" class="full" :src="selectfile" mode=""></image>
			<u-loading-icon v-if="!loading" text="上传中" textSize="18" size="36" :vertical="true"></u-loading-icon>
		</view>

		<!-- <view style="width: 0;height: 0;overflow: hidden;">
			<canvas canvas-id="firstCanvas" style="" :style="{ width: '100%', height: '100%' }" class="canvas"></canvas>
		</view> -->
	</view>
</template>
<script>
	import config from '@/common/config';
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	];
	export default {
		props: {
			fileType: {
				type: Number,
				default () {
					return 3;
				}
			},
			file: {
				type: String,
				default () {
					return '';
				}
			},
			fileMaxNum: {
				type: Number,
				default () {
					return 9
				}
			}
		},
		data() {
			return {
				// 图标
				clearIcon: '',
				selectfile: '',
				VideoOfImagesShow: true, // 页面图片或视频数量超出后，拍照按钮隐藏
				imageList: [], //存放图片的地址
				videoList: [], //视频存放的地址
				fileList: [], //这里需要一个存放所有路径的东西哎无奈呀~~~
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				sourceTypeIndex: 2,
				cameraList: [{
					value: 'back',
					name: '后置摄像头',
					checked: 'true'
				}, {
					value: 'front',
					name: '前置摄像头'
				}],
				cameraIndex: 0, //上传视频时的数量
				maxCount: this.fileMaxNum, //图片和视频允许上传的总数
				loading: true,
				fileMaxNum: this.fileMaxNum
			}
		},

		watch: {
			/* val监听改变的值*/
			file(val) {
				if (val) {
					this.handleFileList(val)
				}
			},
		},
		mounted() {
			this.handleFileList(this.file)
		},
		onUnload() {
			(this.sourceTypeIndex = 2), (this.sourceType = ['拍摄', '相册', '拍摄或相册']);
		},
		methods: {
			handleFileList(data) {
				let fileInfo = data
				this.videoList = []
				this.imageList = []
				if (fileInfo) {
					let fileList = fileInfo.split(",")
					if (fileList.length >= this.fileMaxNum) {
						this.VideoOfImagesShow = false
					}
					fileList.forEach(item => {
						let str = item.split('?')[0]
						if (str.substring(str.length - 3, str.length) == 'mp4') {
							this.videoList.push(item)
						} else {
							console.log(this.imageList)
							this.imageList.push(item)
						}
					})
				}
			},
			//点击上传图片或视频
			chooseVideoImage() {
				//点击获取最大图片数量
				this.maxCount = this.fileMaxNum - this.imageList.length - this.videoList.length
				uni.showActionSheet({
					title: '选择上传类型',
					itemList: ['图片', '视频'],
					success: res => {
						if (res.tapIndex == 0) {
							this.chooseImages();
						} else {
							this.chooseVideo();
						}
					}
				});
			},
			//上传图片
			chooseImages() {
				const that = this
				uni.chooseImage({
					count: this.maxCount, //允许选择的数量
					// sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: async res => {
						this.loading = false
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							const result = await that.uploadFilePromise(res.tempFilePaths[i], 'image')
							this.imageList = this.imageList.concat(result);
						}
						if (this.imageList.length + this.videoList.length >= this.fileMaxNum) {
							this.VideoOfImagesShow = false; //图片上传数量和count一样时，让点击拍照按钮消失
						}
						const list = this.imageList.concat(this.videoList)
						this.fileList = list
						this.$emit("getdata", this.fileList)
						this.loading = true
					},
					fail: res => {
						this.loading = true
					}
				})
			},
			//上传视频
			chooseVideo(index) {
				const that = this
				uni.chooseVideo({
					maxDuration: 30, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
					count: this.maxCount,
					// camera: this.cameraList[this.cameraIndex].value, //'front'、'back'，默认'back'
					// compressed: false, //是否压缩
					sourceType: sourceType[this.sourceTypeIndex],
					success: async res => {
						this.loading = false
						console.log(res)
						const result = await that.uploadFilePromise(res.tempFilePath, 'video')
						console.log(result)
						this.videoList = this.videoList.concat(result);
						if (this.imageList.length + this.videoList.length >= this.fileMaxNum) {
							this.VideoOfImagesShow = false;
						}
						const list = this.imageList.concat(this.videoList)
						this.fileList = list
						this.$emit("getdata", this.fileList)
						this.loading = true
					},
					fail: res => {
						this.loading = true
					}
				})
			},
			//接口转换img
			uploadFilePromise(url, type) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/base/upload/uploadFile',
						filePath: url,
						fileType: type,
						name: 'file',
						formData: {
							type: this.fileType,
							file: url
						},
						header: {
							// #ifdef MP
							"Content-Type": "multipart/form-data",
							// #endif
							"API-User-Token": uni.getStorageSync('userInfo').token
						},
						success: (uploadFileRes) => {
							let res = JSON.parse(uploadFileRes.data);
							console.log(res, 'res')
							resolve(res.data.fileIds[0])
						}
					});
				})
			},
			//预览图片
			previewImage: function(e) {
				uni.previewImage({
					current: e,
					urls: this.imageList
				});
			},
			// 删除图片
			delect(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除该图片',
					success: res => {
						if (res.confirm) {
							this.imageList.splice(index, 1);
							const list = this.imageList.concat(this.videoList)
							this.fileList = list
							this.$emit("delete", this.fileList)
						}
						if (this.imageList.length + this.videoList.length == this.fileMaxNum) {
							this.VideoOfImagesShow = false;
						} else {
							this.VideoOfImagesShow = true;
						}
					}
				});
			},
			// 删除视频
			delectVideo(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除此视频',
					success: res => {
						if (res.confirm) {
							this.videoList.splice(index, 1);
							const list = this.imageList.concat(this.videoList)
							this.fileList = list
							this.$emit("delete", this.fileList)
						}
						if (this.imageList.length + this.videoList.length == this.fileMaxNum) {
							this.VideoOfImagesShow = false;
						} else {
							this.VideoOfImagesShow = true;
						}
					}
				});
			},

			// 调用添加水印的函数
			callAddWaterMart() {
				// 这个是真正的添加水印方法，传入回调是为了解决同时上传多张，会显示相同的图片。
				this.getInfoImage(() => {
					if (this.photoIndex < this.photoArr.length - 1) {
						this.photoIndex++
						this.callAddWaterMart()
					}
				})
			},

			// 这里为了方便写到一个函数里
			getInfoImage(callback) {
				// 小程序没有document，只能在页面中建一个canvas，然后在成功时给他隐藏。
				this.flag = false
				// 这个函数是可以拿到图片的一些信息，宽高等
				uni.getImageInfo({
					// 初始化photoIndex=0，拿到第一张图片，并添加水印
					src: this.photoArr[this.photoIndex],
					success: res => {
						// // 设置画布高度和宽度
						this.canvasWidth = `${res.width}px`
						this.canvasHeight = `${res.height}px`
						//获取当前时间
						let roleNameInfo = date(new Date(), 'long') + '\n' + this.from.data.address
						var ctx = uni.createCanvasContext('imgId')
						ctx.drawImage(this.photoArr[this.photoIndex], 0, 0, res.width, res.height)
						// 为图片添加水印
						ctx.setFontSize(30) //水印字体大小
						ctx.setFillStyle('red') //水印颜色
						// 水印位置
						ctx.fillText(roleNameInfo, 60, res.height - 60)
						// 开始绘制添加水印的图片并显示在页面中
						ctx.draw(false, result => {
							setTimeout(() => {
								//把当前画布指定区域的内容导出生成指定大小的图片，并返回文件路径。在自定义组件下，第二个参数传入自定义组件实例，以操作组件内 <canvas> 组件。
								// 这里主要为了拿到路径
								uni.canvasToTempFilePath({
									canvasId: 'imgId',
									// 设置输出的图片的宽度高度，会加快输出图片时间
									destWidth: res.width,
									destHeight: res.height,
									fileType: 'jpg', //jpg为了压缩
									quality: 0.8, //图片的质量
									success: res => {
										console.log('res', res)
										this.flag = true


										/** 添加上传进度和图片路径 */
										this.currentImgList.push({
											path: res.tempFilePath,
											uploadPercent: 0
										})
										// 上传图片
										this.uploadfile(res.tempFilePath)
										// 给所有的图片添加水印
										callback()
									},
									fail: err => {
										uni.hideLoading()
										// this.$u.toast('上传错误')
									}
								})
							}, 500)
						})
					},
					fail: err => {
						console.log(err)
					}
				})
			}
		}
	}
</script>
<style lang="scss">
	/* 统一上传后显示的盒子宽高比 */
	.box-mode
	{
	width:
	27vw;
	height:
	27vw;
	display:
	flex;
	align-items:
	center;
	justify-content:
	center;
	border-radius:
	8rpx;
	overflow:
	hidden;
	}
	.full
	{
	width:
	100%;
	height:
	100%;
	background-size:
	cover;
	}
	.clear
	{
	border-radius:
	12px;
	}
	.up-page
	{
	display:
	flex;
	flex-wrap:
	wrap;
	display:
	flex;
	width:
	100%;
	.show-box:nth-child(3n)
	{
	margin-right:
	0;
	}
	.show-box
	{
	position:
	relative;
	margin-bottom:
	4vw;
	margin-right:
	4vw;
	@extend
	.box-mode;
	.delect-icon
	{
	height:
	40rpx;
	width:
	40rpx;
	position:
	absolute;
	right:
	0rpx;
	top:
	0rpx;
	z-index:
	0;
	margin:
	4px;
	}
	}
	}
</style>
